package com.shanhai.wallpapers.fragments.Preview

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.graphics.toColorInt
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.shanhai.wallpapers.databinding.FragmentPreviewBinding
import com.shanhai.wallpapers.extensions.applyStatusBarPadding

class PreviewFragment : Fragment() {
    private var mBinding: FragmentPreviewBinding? = null
    private val binding get() = requireNotNull(mBinding)
    private val args: PreviewFragmentArgs by navArgs()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentPreviewBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.previewContent.applyStatusBarPadding()
        init()
    }

    private fun init() {
        setListener()
        loadWallpaperView()
    }

    private fun loadWallpaperView() {
        with(args.photo) {
            avgColor?.let { color ->
                binding.imageWallpaperPreview.setBackgroundColor(color.toColorInt())
            }
            source?.large2x?.let { previewUrl ->
                Glide.with(binding.root)
                    .load(previewUrl)
                    .transition(DrawableTransitionOptions.withCrossFade(500))
                    .into(binding.imageWallpaperPreview)
            }
        }
    }

    private fun setListener() {
        binding.imageBack.setOnClickListener {
            findNavController().popBackStack()
        }
    }
}